﻿using Dapper;
using Estsh.Core.Base;
using Estsh.Core.Dapper;
using Estsh.Core.Model.EnumUtil;
using Estsh.Core.Model.Extend.Models;
using Estsh.Core.Models;
using Estsh.Core.Repositories;
using Estsh.Core.Wms.IRepositories;
using System.Data;
using System.Text;

namespace Estsh.Core.Wms.Repositories
{
    /// <summary>
    /// NC入库
    /// </summary>
    public class NCInStockRepository : BaseRepository<BaseEntity>, INCInStockRepository
    {
        public NCInStockRepository(DapperDbContext _dapperDbContext) : base(_dapperDbContext)
        {

        }
        /// <summary>
        /// 获取NC入库单据信息
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public List<WmsMoveHeader> GetNCInStockOrderList(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT  a.order_no,b.enum_desc AS order_type_desc,a.create_time,d.emp_no,a.factory_code,a.enabled FROM dbo.wms_move_header a (nolock) ");
                SqlStringBuilder.Append("LEFT JOIN dbo.sys_enum b (nolock) ON a.order_type = b.enum_value AND b.enum_type = 'wms_move_order_type' ");
                //SqlStringBuilder.Append("LEFT JOIN wms_move_detail c ON a.order_no = c.order_no ");
                SqlStringBuilder.Append("LEFT JOIN dbo.sys_emp d (nolock) ON a.create_userid = d.emp_id ");
                SqlStringBuilder.Append("WHERE a.order_no like '%" + orderNo + "%' AND order_status in ('10','30') AND order_type = 40 and a.enabled = 'Y' ");

                List<WmsMoveHeader> wmsMoves = dbConn.Query<WmsMoveHeader>(SqlStringBuilder.ToString()).ToList();
                return wmsMoves;
            }
        }

        /// <summary>
        /// 获取NC入库单据信息通过订单号
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public List<WmsMoveHeader> GetNCInStockOrderListByOrderNo(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT a.order_no,b.enum_desc AS order_type_desc,CONVERT(INT, c.qty) qty,CONVERT(INT, c.pick_qty) pick_qty,c.part_no ,a.create_userid,a.create_time,c.src_zone_id,c.src_zone_name,d.emp_no,a.factory_code,p.part_spec FROM dbo.wms_move_header a (nolock) ");
                SqlStringBuilder.Append("LEFT JOIN dbo.sys_enum b (nolock) ON a.order_type=b.enum_value AND	b.enum_type='wms_move_order_type'  ");
                SqlStringBuilder.Append("LEFT JOIN dbo.wms_move_detail c (nolock) ON a.order_no=c.order_no ");
                SqlStringBuilder.Append("LEFT JOIN dbo.sys_emp d (nolock) ON a.create_userid=d.emp_id ");
                SqlStringBuilder.Append("LEFT JOIN dbo.sys_part p (nolock) ON c.part_no=p.part_no ");
                SqlStringBuilder.Append("WHERE a.order_no = '" + orderNo + "' AND order_type=40 and a.enabled='Y' ");

                List<WmsMoveHeader> wmsMoves = dbConn.Query<WmsMoveHeader>(SqlStringBuilder.ToString()).ToList();
                return wmsMoves;
            }
        }
        /// <summary>
        /// 库位信息
        /// </summary>
        /// <param name="locateName"></param>
        /// <returns></returns>
        public List<SysLocate> GetLocateByLocateName(string locateName)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM dbo.sys_locate (nolock) WHERE locate_name = '" + locateName + "'");
                List<SysLocate> sysLocates = dbConn.Query<SysLocate>(stringBuilder.ToString()).ToList();
                return sysLocates;
            }
        }

        /// <summary>
        /// 根据库位获取库存在库数量
        /// </summary>
        /// <param name="locateName"></param>
        /// <returns></returns>
        public SysStock GetStocQtySumByLocateName(string locateName)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
				// stringBuilder.Append("  SELECT SUM(qty) as qty FROM dbo.sys_stock (nolock) WHERE locate_name = '" + locateName + "' AND status IN ('50','60','80') and enabled='Y' ");
				stringBuilder.Append("  SELECT SUM(qty) as qty FROM dbo.sys_stock (nolock) WHERE locate_name = '" + locateName + "' AND status=90 and enabled='Y' ");//90: 条码NC入库
				SysStock sysStocksLocateCount = dbConn.QueryFirstOrDefault<SysStock>(stringBuilder.ToString());//库位在库数
                return sysStocksLocateCount;
            }
        }
        public List<SysStock> GetStocInfoByCartonNo(string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT a.vendor_id, a.vendor_code, a.carton_no, a.locate_id, a.locate_name,a.qty, a.status, a.enabled,b.part_id,b.part_no,b.part_spec, b.part_spec, a.warehouse_id,a.warehouse_name,a.zone_id,a.zone_name,c.enum_desc AS stock_status " +
                                      ",a.unit,a.factory_id,a.factory_code FROM sys_stock a (nolock) LEFT JOIN dbo.sys_part b (nolock) ON a.part_no = b.part_no LEFT JOIN dbo.sys_enum c (nolock) ON a.status=c.enum_value AND enum_type LIKE '%sys_stock_status%' WHERE a.carton_no='" + cartonNo + "' ");
                List<SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();
                return sysStocks;
            }
        }
        public List<SysLocate> GetLocatePartByLocateName(string locateName)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT a.*,b.part_id,b.part_no FROM dbo.sys_locate a (nolock) LEFT JOIN sys_locate_part b (nolock) ON a.locate_id = b.locate_id  WHERE a.locate_name = '" + locateName + "' and a.enabled='Y'");
                List<SysLocate> sysLocates = dbConn.Query<SysLocate>(stringBuilder.ToString()).ToList();
                return sysLocates;
            }
        }


        //根据库位名称获取目标信息
        public List<SysLocate> GetLocateZoneByLocateName(string locateName)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("select a.*,b.erp_warehouse from sys_locate as a (nolock) left join sys_zone as b (nolock) on  a.zone_id=b.zone_id ");
                SqlStringBuilder.Append("where a.locate_name ='" + locateName + "' ");
                List<SysLocate> sysLocates = dbConn.Query<SysLocate>(SqlStringBuilder.ToString()).ToList();
                return sysLocates;
            }
        }

        //根据单号获取NC入库单信息
        public List<WmsMoveHeader> GetMoveHeaderByOrderNo(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder(1024);
                stringBuilder.Append("SELECT * FROM dbo.wms_move_header (nolock) WHERE order_no = '" + orderNo + "' AND order_status in ('10','30') AND order_type=40 and enabled='Y'");
                List<WmsMoveHeader> wmsMoveHeaders = dbConn.Query<WmsMoveHeader>(stringBuilder.ToString()).ToList();
                return wmsMoveHeaders;
            }
        }

        //根据单号和零件号查询单据明细信息
        public List<WmsMoveDetail> GetMoveDetailByOrderNoPartNo(string orderNo, string partNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM dbo.wms_move_detail (nolock) WHERE order_no='" + orderNo + "' and part_no='" + partNo + "' and enabled='Y'");
                List<WmsMoveDetail> wmsMoveDetails = dbConn.Query<WmsMoveDetail>(stringBuilder.ToString()).ToList();
                return wmsMoveDetails;
            }
        }

        //根据单号获取条码信息
        public List<WmsMoveSn> GetMoveSnByOrderNo(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM dbo.wms_move_sn (nolock) WHERE order_no='" + orderNo + "' and status=" + (int)WmsEnumUtil.MoveOrderSnStatus.CREATE);
                List<WmsMoveSn> moveSnCreates = dbConn.Query<WmsMoveSn>(stringBuilder.ToString()).ToList();
                return moveSnCreates;
            }
        }

        //根据单号、条码获取条码信息
        public List<WmsMoveSn> GetMoveSnByOrderNoCarton(string orderNo, string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM dbo.wms_move_sn (nolock) WHERE order_no='" + orderNo + "' and status=" + (int)WmsEnumUtil.MoveOrderSnStatus.CREATE + " and carton_no ='" + cartonNo + "'");
                List<WmsMoveSn> wmsMoveSns = dbConn.Query<WmsMoveSn>(stringBuilder.ToString()).ToList();
                return wmsMoveSns;
            }
        }
        //根据单号获取NC入库单信息
        public List<WmsMoveHeader> GetMoveHeaderInfoByOrderNo(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT a.order_no,b.enum_desc AS order_type_desc,CONVERT(INT, c.qty) qty,CONVERT(INT, c.pick_qty) pick_qty,c.part_no ,a.create_userid,a.create_time,c.src_zone_id,c.src_zone_name,d.emp_no,a.factory_code,p.part_spec FROM dbo.wms_move_header a (nolock) ");
                SqlStringBuilder.Append("LEFT JOIN dbo.sys_enum b (nolock) ON a.order_type=b.enum_value AND	b.enum_type='wms_move_order_type'  ");
                SqlStringBuilder.Append("LEFT JOIN dbo.wms_move_detail c (nolock) ON a.order_no=c.order_no ");
                SqlStringBuilder.Append("LEFT JOIN dbo.sys_emp d (nolock) ON a.create_userid=d.emp_id ");
                SqlStringBuilder.Append("LEFT JOIN dbo.sys_part p (nolock) ON c.part_no=p.part_no ");
                SqlStringBuilder.Append("WHERE a.order_no = '" + orderNo + "' AND order_status in ('10','30') AND order_type=40 and a.enabled='Y'");
                List<WmsMoveHeader> wmsMoves = dbConn.Query<WmsMoveHeader>(SqlStringBuilder.ToString()).ToList();
                return wmsMoves;
            }
        }
        //根据单号获取NC入库单数量总数
        public List<WmsMoveHeader> GetMoveHeaderQtySumByOrderNo(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT SUM( CONVERT(INT, c.qty)) qty,SUM(CONVERT(INT, c.pick_qty)) pick_qty,c.part_no,c.part_spec FROM dbo.wms_move_header a (nolock) ");
                SqlStringBuilder.Append("LEFT JOIN dbo.wms_move_detail c (nolock) ON a.order_no=c.order_no ");
                SqlStringBuilder.Append(" WHERE a.order_no = '" + orderNo + "' AND order_status in ('10','30') AND order_type=40 and a.enabled='Y' group by c.part_no,c.part_spec");

                List<WmsMoveHeader> wmsMoves = dbConn.Query<WmsMoveHeader>(SqlStringBuilder.ToString()).ToList();
                return wmsMoves;
            }
        }

        //获取完成信息提交数据
        public List<WmsMoveDetail_Extend> GetFinishMoveDetailByOrderNo(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT SUM(CONVERT(INT, c.pick_qty)) pick_qty,c.part_no,src_erp_warehouse,dest_erp_warehouse,plan_date,plan_time,a.factory_code,a.order_no,a.ref_order_no FROM dbo.wms_move_header a (nolock) ");
                SqlStringBuilder.Append("LEFT JOIN dbo.wms_move_detail c (nolock) ON a.order_no=c.order_no ");
                SqlStringBuilder.Append(" WHERE a.order_no = '" + orderNo + "' AND c.item_status <> '40' and a.enabled='Y' group by c.part_no,src_erp_warehouse,dest_erp_warehouse,plan_date,plan_time,a.factory_code,a.order_no,a.ref_order_no");

                List<WmsMoveDetail_Extend> wmsMoves = dbConn.Query<WmsMoveDetail_Extend>(SqlStringBuilder.ToString()).ToList();
                return wmsMoves;
            }
        }

		//获取完成信息提交数据自动提交
		public List<WmsMoveDetail_Extend> GetFinishMoveDetailByOrderNoAutoPostBack(string orderNo)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();
				StringBuilder SqlStringBuilder = new StringBuilder(1024);
				SqlStringBuilder.Append("SELECT SUM(CONVERT(INT, c.pick_qty)) pick_qty,c.part_no,src_erp_warehouse,dest_erp_warehouse,plan_date,plan_time,a.factory_code,a.order_no,a.ref_order_no FROM dbo.wms_move_header a (nolock) ");
				SqlStringBuilder.Append("LEFT JOIN dbo.wms_move_detail c (nolock) ON a.order_no=c.order_no ");
				SqlStringBuilder.Append(" WHERE a.order_no = '" + orderNo + "' AND c.item_status = '40' and a.enabled='Y' group by c.part_no,src_erp_warehouse,dest_erp_warehouse,plan_date,plan_time,a.factory_code,a.order_no,a.ref_order_no");

				List<WmsMoveDetail_Extend> wmsMoves = dbConn.Query<WmsMoveDetail_Extend>(SqlStringBuilder.ToString()).ToList();
				return wmsMoves;
			}
		}

		//获取零件号信息
		public SysPart GetPartNOInfoByPartNo(string partNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("    SELECT * from sys_part (nolock) where part_no='" + partNo + "' ");
                SysPart sysParts = dbConn.QueryFirstOrDefault<SysPart>(SqlStringBuilder.ToString());
                return sysParts;
            }
        }

        //事务批量执行添加、修改
        public int SQLTransaction(List<string> sqlStrings, List<DynamicParameters> parameterList)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                if (dbConn.State == ConnectionState.Closed)
                {
                    dbConn.Open();
                }
                //执行事务
                IDbTransaction transaction = dbConn.BeginTransaction();
                if (parameterList == null || parameterList.Count == 0)
                {
                    try
                    {
                        for (int i = 0; i < sqlStrings.Count; i++)
                        {
                            dbConn.Execute(sqlStrings[i], null, transaction);
                        }
                        transaction.Commit();
                        return 1;
                    }
                    catch (Exception exception)
                    {
                        transaction.Rollback();
                        return 0;
                    }
                }
                else
                {
                    try
                    {
                        for (int i = 0; i < sqlStrings.Count; i++)
                        {
                            dbConn.Execute(sqlStrings[i], parameterList[i], transaction);
                        }
                        transaction.Commit();
                        return 1;
                    }
                    catch (Exception exception)
                    {
                        transaction.Rollback();
                        return 0;
                    }
                }
            }
        }
    }
}
